package com.Team7.controller;

import com.Team7.call.FileTextCall;
import com.Team7.domain.OFFile;
import com.Team7.factory.DiskFactory;
import com.Team7.util.FileUtil;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;

import java.util.Optional;

public class FileTextController {

    private Stage stage;
    private FileTextCall fileTextCall;
    private OFFile ofFile;

    @FXML
    private TextArea ta_filetext;


    public FileTextController(FileTextCall fileTextCall, OFFile ofFile){
        this.stage=new Stage();
        this.fileTextCall=fileTextCall;
        this.ofFile=ofFile;

        try{
            FXMLLoader fxmlLoader=new FXMLLoader(getClass().getResource("../fxml/FileText.fxml"));
            fxmlLoader.setController(this);
            Scene scene=new Scene(fxmlLoader.load());
            stage.setScene(scene);

            if(ofFile.getFlag()==1){

                stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
                    @Override
                    public void handle(WindowEvent event) {
                        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
                        alert.setHeaderText("Do you want to save it?");
                        alert.setTitle("保存");
                        Optional<ButtonType> result = alert.showAndWait();
                        if (result.get() == ButtonType.OK){

                            System.out.println(ta_filetext.getText());
                            FileUtil.updateFileText(DiskFactory.getDisk(),ofFile,ta_filetext.getText());

                            System.out.println("保存");
                        } else {
                            // ... user chose CANCEL or closed the dialog
                        }
                        fileTextCall.getStatus("success");
                    }
                });
            }else{

            }




        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void show(){
        stage.show();
    }

    @FXML
    private void  initialize(){

        ta_filetext.setText(FileUtil.getFileText(DiskFactory.getDisk(),ofFile));
        if(ofFile.getFlag()==0){
            ta_filetext.setEditable(false);
        }
    }



}
